package com.easwift.qsp.das.cjy;
import java.io.BufferedInputStream;
import java.util.Date;
import java.util.List;

import cn.hutool.core.date.DateUtil;
import com.easwift.qsp.das.pool.DataPool;
import com.easwift.qsp.enums.DeviceTypeEnum;
import com.easwift.qsp.enums.MonitorItemEnum;
import com.easwift.qsp.util.BitUtils;
import com.easwift.qsp.util.DataSourceUtils;
import com.easwift.qsp.util.LogUtils;
import org.springframework.util.CollectionUtils;

/**
 * 激光测距仪读数据线程
 * @author Administrator
 *
 */
public class CJYSocketReadThread extends Thread{

	private BufferedInputStream bis;
	// 每个线程对应一个数据池，防止多个设备串数据
	private ThreadLocal<DataPool> dataPool = new ThreadLocal<DataPool>() {

		@Override
		protected DataPool initialValue() {
			// 单例bean中注入多例bean，这种方式最简单
			DataPool dPool = new DataPool();
			/*p:head="d7ef" p:crcOneLength="8" p:lookupBefore="true" p:getAll="true" abstract="true"*/
			dPool.setHead("d7ef");
			dPool.setCrcOneLength(8);
			dPool.setLookupBefore(true);
			dPool.setGetAll(true);
			dPool.setFrameLength(24);
			dPool.setDataLength(8);
			return dPool.init();
		}

	};

	public CJYSocketReadThread(BufferedInputStream bis) {
		super();
		this.bis = bis;
	}

	@Override
	public void run(){
		try{
			while(true){
				if(bis.available() != 0){
					byte[] bytes = new byte[bis.available()];
					bis.read(bytes,0,bis.available());
					System.out.print("端口8091读取到数据：");
					LogUtils.printFrame(bytes);

					// 先得到这个线程，将数据加入池中
					dataPool.get().add(bytes);
					// 从池中取得完整的所有帧数据
					List<byte[]> frameList = dataPool.get().get();

					if (CollectionUtils.isEmpty(frameList)) {
						return;
					}

					//循环每个数据帧
					frameList.forEach(frame -> {
						//设备地址
						int address = Byte.toUnsignedInt(frame[0]) + (Byte.toUnsignedInt(frame[1]) << 8);
						//位移
						double d = 0;
						//温度
						double oc = 0;
						//时间
						String now = DateUtil.now();

						byte[] bbs = new byte[4];
						System.arraycopy(frame,14,bbs,0,4);
						bbs = BitUtils.reverseArray(bbs);
						d = BitUtils.byteArrayToFloat(bbs);

						System.arraycopy(frame,18,bbs,0,4);
						bbs = BitUtils.reverseArray(bbs);
						oc = BitUtils.byteArrayToFloat(bbs);

						System.out.println(String.format("位移：%s",d));
						System.out.println(String.format("温度：%s",oc));

						String sql = String.format("insert into tb_device_cjdata (address,temp,distance,createtime) values (%s,%s,%s,%s)",String.valueOf(address),oc,d,"'"+now+"'");
						DataSourceUtils.getJdbcTemplate().execute(sql);

					});
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}

}
